package com.spsy.order.service.impl;

import com.alibaba.fastjson2.JSON;
import com.spsy.common.core.domain.R;
import com.spsy.order.domain.Order;
import com.spsy.order.param.req.OrderReq;
import com.spsy.order.service.IOrderService;
import com.spsy.order.service.OrderOptsService;
import com.spsy.pay.api.SpsyPayProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author: liuzhiping
 * @date: 2025/1/15 14:53
 **/
@Slf4j
@Service
public class OrderOptsServiceImpl implements OrderOptsService {

    @Autowired
    private SpsyPayProvider spsyPayProvider;


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public R execOrder(OrderReq orderReq ) {

        //控制刷单
        //通过产品id+用户id来控制
        String key = orderReq.getUserId()+"_"+orderReq.getProductId();

        log.info("订单key:{}",key);

        if(this.redisTemplate.hasKey(key)){
            return R.fail("下单太频繁，稍后再操作");
        }
        //设置缓存时间
        this.redisTemplate.opsForValue().set(key,1,10, TimeUnit.SECONDS);

        System.out.println("订单系统请求1 支付系统 获取二维码 orderId="+orderReq.getOrderId());

        //R r =  this.spsyPayProvider.payOrder(orderReq.getOrderId());


        //生产订单数据 往订单表中插入一条数据
        //往rabbitmq 延迟队列里面写数据(a100)

        Order order = Order.builder()
                .orderId(Long.valueOf(orderReq.getOrderId()))
                .orderStatus("1")
                .orderNumber("a100")
                .userId(Long.valueOf("1000"))
                .totalAmount(BigDecimal.ONE)
                .build();
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        int insertCount = this.orderService.insertOrder(order);


        log.info("当前时间：{}，2206a 发送一条时长{}毫秒的消息给延迟队列：{}-{}", new Date(),orderReq.getOrderId());
        rabbitTemplate.convertAndSend("lzp_delayed_queue2206a","lzp_delayed_key2206a",orderReq.getOrderId(), msg -> {
            //发送消息的时候延迟时长
            msg.getMessageProperties().setDelay(20000);
            // message= 订单号
            //插入数据订单表中一个数据
            //订单状态设置成未支付
            return msg;
        });


        com.spsy.common.vo.OrderReq orderReq1 = new com.spsy.common.vo.OrderReq();
        BeanUtils.copyProperties(orderReq,orderReq1);

        log.info("orderReq1:{}",JSON.toJSONString(orderReq1));

        R r =  this.spsyPayProvider.payOrder(orderReq1);

        System.out.println("订单系统请求2 支付系统 获取二维码 r="+ JSON.toJSONString(r));

        return r;

    }
}
